package com.rou.im.boot.starter.server;

import com.rou.im.boot.starter.server.netty.EventLoopGroupManager;
import com.rou.im.boot.starter.server.netty.ServerBootstrapBean;
import com.rou.im.boot.starter.server.netty.ServerSocketChannelSelector;
import com.rou.im.boot.starter.server.netty.config.NettyConfigProperties;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-05-03 13:45
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(IMServerMarkerConfiguration.Marker.class)
@Import({IMServerInitializerConfiguration.class})
@EnableConfigurationProperties({ NettyConfigProperties.class})
public class IMServerAutoConfiguration {
    private final NettyConfigProperties config;

    @Autowired
    public IMServerAutoConfiguration(NettyConfigProperties config) {
        this.config = config;
    }

    @Bean
    public ServerBootstrapBean serverBootstrapBean(EventLoopGroupManager eventLoopGroupManager,ServerSocketChannelSelector serverSocketChannelSelector,ChannelInitializerPostProcessor channelInitializerPostProcessor){
        return new ServerBootstrapBean(config,eventLoopGroupManager,serverSocketChannelSelector,channelInitializerPostProcessor);
    }

    @Bean(name = "eventLoopGroupManager")
    public EventLoopGroupManager eventLoopGroupManager(){
        return new EventLoopGroupManager(config);
    }

    @Bean(name = "socketChannelSelector")
    public ServerSocketChannelSelector socketChannelSelector(){
        return new ServerSocketChannelSelector();
    }

    @Bean
    @ConditionalOnMissingBean
    public ChannelInitializerPostProcessor channelInitializerPostProcessor(){
        return ch -> {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new StringDecoder());
            pipeline.addLast(new StringEncoder());
        };
    }


}
